package com.ruoyi.common.core.config.mybatis;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @Explain: 通过指定的字段名删除数据
 * @Author: Cao.Yu
 * @Date: 2023/6/8 15:02
 */
public class SelectByFieldMethod extends AbstractMethod {

    private static final String METHOD_NAME = "selectByField";

    protected SelectByFieldMethod() {
        super(METHOD_NAME);
    }


    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "<script>select %s from %s where ${fieldName} = #{fieldValue}</script>";
        if (tableInfo.getFieldList().stream().anyMatch(x -> "company_id".equals(x.getColumn()))) {
            sql = "<script>select %s from %s where ${fieldName} = #{fieldValue} and company_id = #{companyId}</script>";
        }
        String fieldSql = prepareFieldSql(tableInfo);
        final String sqlResult = String.format(sql, fieldSql, tableInfo.getTableName());
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        return this.addSelectMappedStatementForTable(mapperClass, METHOD_NAME, sqlSource, tableInfo);
    }

    private String prepareFieldSql(TableInfo tableInfo) {
        StringBuilder fieldSql = new StringBuilder();
        fieldSql.append(tableInfo.getKeyColumn()).append(",");
        tableInfo.getFieldList().forEach(x -> fieldSql.append(x.getColumn()).append(","));
        fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
        return fieldSql.toString();
    }

}
